package cn.psvmc.cxzapi.service.store;

import cn.psvmc.cxzapi.config.mybatisplus.service.impl.AbstractService;
import cn.psvmc.cxzapi.exception.ServiceException;
import cn.psvmc.cxzapi.mapper.store.TStoreDetailMapper;
import cn.psvmc.cxzapi.mapper.store.TStoreMapper;
import cn.psvmc.cxzapi.mapper.system.TUserMapper;
import cn.psvmc.cxzapi.mapper.system.TUserRoleMapper;
import cn.psvmc.cxzapi.model.common.SearchEntity;
import cn.psvmc.cxzapi.model.store.*;
import cn.psvmc.cxzapi.model.system.TUser;
import cn.psvmc.cxzapi.model.system.TUserRole;
import cn.psvmc.cxzapi.service.alipay.AlipayCreate;
import cn.psvmc.cxzapi.service.system.ServiceUtil;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.istack.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 商家表 服务实现类
 * @Author auto
 * @Date 2024-08-14
 */
@Service
public class TStoreService extends AbstractService<TStoreMapper, TStore> {

    @Resource
    private TStoreMapper tStoreMapper;
    @Resource
    private TStoreDetailMapper storeDetailMapper;
    @Resource
    private TUserMapper userMapper;
    @Resource
    private TUserRoleMapper userRoleMapper;
    @Resource
    private TAccountService accountService;
    @Resource
    private ServiceUtil serviceUtil;

    /**
    * @Date auto 2024-08-14 新增商家表
    * @Param tStore 商家表
    * @Return int
    */
    @Transactional(rollbackFor = Exception.class)
    public void add(TStore tStore) {
        checkStoreName(tStore);//校验商家名称是否存在
        //添加商家
        tStore.setCheckStatus(0);
        tStoreMapper.insert(tStore);
        Integer storeid = tStore.getStoreid();

        //添加商家详情
        TStoreDetail detail = tStore.getDetail();
        if (detail == null) {
            detail = new TStoreDetail();
        }
        detail.setStoreid(storeid);
        storeDetailMapper.insert(detail);

        saveUser(tStore);//保存商家用户
        saveAccount(storeid);//保存商家账户
    }

    //校验商家名称是否存在
    private void checkStoreName(TStore tStore) {
        Integer num = tStoreMapper.checkStoreName(tStore.getStorename());//校验商家名称是否存在
        if (num > 0) {
            throw new ServiceException("商家名称已存在！");
        }
    }

    //保存商家账户
    private void saveAccount(Integer storeid) {
        List<TAccount> accounts = new ArrayList<>();
        //租金账户
        TAccount account1 = new TAccount();
        account1.setAccountType(1);
        account1.setStoreid(storeid);
        accounts.add(account1);

        //质保金账户
        TAccount account2 = new TAccount();
        account2.setAccountType(2);
        account2.setStoreid(storeid);
        accounts.add(account2);
        accountService.saveBatch(accounts);
    }

    //保存商家用户
    private void saveUser(TStore tStore) {
        TUser tUser = new TUser();
        tUser.setUsername(tStore.getStorelink());
        tUser.setUserphone(tStore.getStorephone());
        tUser.setUsertype(2);
        tUser.setStoreid(tStore.getStoreid());
        String loginpwd = tUser.getLoginpwd();
        if (ToolUtils.isEmpty(loginpwd)) {
            loginpwd = "123456";
        }
        tUser.setLoginpwd(ToolUtils.getMD5Pwd(loginpwd));
        userMapper.insert(tUser);
        TUserRole ur = new TUserRole();
        ur.setRoleid(2);//待审核商家
        ur.setUserid(tUser.getUserid());
        userRoleMapper.insert(ur);
    }

    /**
    * @Date auto 2024-08-14 更新商家表
    * @Param tStore 商家表模型
    * @Return int
    */
    @Transactional(rollbackFor = Exception.class)
    public void edit(TStore tStore) {
        TStore store = checkObjAndVersion(tStore);//校验商家和版本号
        String storename = tStore.getStorename();
        if (ToolUtils.isNotEmpty(storename) && !storename.equals(store.getStorename())) {
            checkStoreName(tStore);//校验商家名称是否存在
        }
        String storephone = tStore.getStorephone();
        String storelink = tStore.getStorelink();
        Map<String, Object> user = userMapper.getUserByStoreIdAndPhone(tStore.getStoreid(), storephone);//校验商家用户是否存在
        if (user == null) {
            saveUser(tStore);//保存商家用户
        } else if (!user.get("username").equals(storelink) || user.get("deleted").equals(1)) {
            TUser tUser = new TUser();
            tUser.setUserid(ToolUtils.objToInteger(user.get("userid")));
            tUser.setUsername(storelink);
            tUser.setDeleted(0);
            userMapper.updateById(tUser);//更新商家用户
        }

        tStore.setCheckStatus(0);
        // 字段为null 不更新
        tStoreMapper.updateById(tStore);

        //更新商家详情
        TStoreDetail detail = tStore.getDetail();
        if (detail != null) {
            storeDetailMapper.updateById(detail);
        }
    }

    //校验商家和版本号
    public TStore checkObjAndVersion(TStore tStore) {
        // 通过id查询数据处理 详情
        TStore originTStore = tStoreMapper.selectById(tStore.getStoreid());
        if (originTStore == null) {
            throw new ServiceException("未查询到对应的商家表信息！");
        }

        // 比较数据版本号
        if (!originTStore.getRversion().equals(tStore.getRversion())) {
            throw new ServiceException("数据已更新，请刷新后重试！");
        }
        return originTStore;
    }

    /**
    * @Date auto 2024-08-14 查询商家表详情
    * @Param id 唯一id
    * @Return cn.psvmc.cxzapi.model.store.TStore
    */
    public Map<String, Object> detail(Integer id) {
        Map<String, Object> map = tStoreMapper.findById(id);
        if (map == null) {
            throw new ServiceException("未查询到对应的商家信息！");
        }
        map.put("detail", storeDetailMapper.findByStoreId(id));
        return map;
    }

    /**
     * @Description 平台管理列表
     * @Date 2024/8/14 21:03
     * @Author YWX
     * @Param [iPage, entity]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map>
     **/
    public IPage<Map> list(Page<TStore> iPage, SearchEntity entity){
        return tStoreMapper.listAll(iPage, entity);
    }

    /**
     * @Description 审核
     * @Date 2024/8/14 21:09
     * @Author YWX
     * @Param [tStore]
     * @Return void
     **/
    public void check(TStore tStore) {
        checkObjAndVersion(tStore);//校验商家和版本号
        if (tStore.getCheckStatus().equals(1)) {//审核通过，变更为已认证
            tStore.setStoretype(2);
            userRoleMapper.updateByStoreId(tStore.getStoreid(), 3);//更新用户角色为普通商家
        } else {//审核拒绝，变更为认证失败
            tStore.setStoretype(3);
        }
        tStore.setCheckId(serviceUtil.getUserId());
        tStore.setCheckTime(LocalDateTime.now());
        tStoreMapper.updateById(tStore);
    }

    /**
     * @Description 商家选择列表
     * @Date 2024/8/21 15:57
     * @Author YWX
     * @Param [entity]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listForSel(SearchEntity entity) {
        return tStoreMapper.listForSel(entity);
    }

    /**
     * @Description 获取商家服务信息
     * @Date 2024/9/27 12:55
     * @Author YWX
     * @Param []
     * @Return java.util.Map<java.lang.String, java.lang.Object>
     **/
    public Map<String, Object> getService() {
        Integer storeId = getStoreId();
        return storeDetailMapper.getService(storeId);
    }

    private @NotNull Integer getStoreId() {
        Integer storeId = serviceUtil.getStoreId();
        if (storeId == null) {
            throw new ServiceException("未查询到商家信息！");
        }
        return storeId;
    }

    /**
     * @Description 更新商家服务信息
     * @Date 2024/9/27 13:00
     * @Author YWX
     * @Param [detail]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void editService(TStoreDetail detail) {
        Integer storeid = getStoreId();
        detail.setStoreid(storeid);
        TStore tStore = tStoreMapper.selectById(storeid);
        if (tStore == null) {
            throw new ServiceException("未查询到商家信息！");
        }
        String storename = detail.getStorename();
        boolean modify = false;
        if (ToolUtils.isNotEmpty(storename) && !storename.equals(tStore.getStorename())) {
            modify = true;
        }
        String storelogo = detail.getStorelogo();
        String resourceid = null;
        if (ToolUtils.isNotEmpty(storelogo) && !storelogo.equals(tStore.getStorelogo())) {
            modify = true;
            resourceid = AlipayCreate.logoUpload(storelogo);
        }
        if (modify) {
            TStore store = new TStore();
            store.setStoreid(storeid);
            store.setStorename(storename);
            store.setStorelogo(storelogo);
            store.setResourceid(resourceid);
            tStoreMapper.updateById(store);
        }
        storeDetailMapper.editService(detail);
    }
}
